package com.java.wx.controller;

import com.java.bean.Courier;
import com.java.bean.Message;
import com.java.bean.User;
import com.java.exception.DuplicateException;
import com.java.exception.ExceptionStateEnum;
import com.java.mvc.Body;
import com.java.mvc.View;
import com.java.service.CourierService;
import com.java.service.UserService;
import com.java.util.JSONUtil;
import com.java.util.RandomUtil;
import com.java.util.UserUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("all")
public class UserController {

//    @Body("/wx/.do")
//    public String (HttpServletRequest req, HttpServletResponse resp) {

    // 7天内自动登录
    @View("/log/autoLogin.do")
    public String autoLogin(HttpServletRequest req, HttpServletResponse resp) {
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            if ("autoLogin".equals(cookie.getName())) {
                String value = cookie.getValue();
                if ("false".equals(value)) {
                    return "/login.html";
                } else {
                    User user = UserService.getUserByEmail(value);
                    if (user == null) {
                        Courier courier = CourierService.getCourierByEmail(value);
                        if (courier == null) {
                            return "/login.html";
                        }
                        req.getSession().setAttribute("courier", courier);
                        return "/";
                    }
                    req.getSession().setAttribute("user", user);
                    return "/";
                }
            }
        }
        return "/login.html";
    }

    @Body("/wx/updateUserInfo.do")
    public String updateUserInfo(HttpServletRequest req, HttpServletResponse resp) {
        int id = Integer.parseInt(req.getParameter("id"));
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
        if (email != null) {
            String sysCode = (String) req.getSession().getAttribute(email);
            if (sysCode != null) {
                if (!sysCode.equals(code)) {
                    return new Message(-7, "验证码不匹配").toJSON();
                }
            } else return new Message(-8, "请先发送验证码").toJSON();
        }
        User user = UserUtil.getUser(req);
        Courier courier = UserUtil.getCourier(req);
        return updateUser(user, courier, name, password, phone, email, id);
    }

    private String updateUser(User user, Courier courier, String name, String password, String phone, String email, int id) {
        if (user != null) {
            String oldName = user.getName();
            String oldPassword = user.getPassword();
            String oldPhone = user.getPhone();
            String oldEmail = user.getEmail();
            if (password != null)
                user.setPassword(password);
            if (phone != null && phone.equals("未绑定"))
                user.setPhone(null);
            if (name != null)
                user.setName(name);
            if (email != null)
                user.setEmail(email);
            try {
                return new Message(UserService.update(id, user), "修改成功！").toJSON();
            } catch (DuplicateException e) {
                user.setPassword(oldPassword);
                user.setPhone(oldPhone);
                user.setName(oldName);
                user.setEmail(oldEmail);
                return new Message(e.getType().getVal(), getMessage(e.getType())).toJSON();
            }
        } else {
            return updateCourier(courier, name, password, phone, email, id);
        }
    }

    private String updateCourier(Courier courier, String name, String password, String phone, String email, int id) {
        if (courier != null) {
            String oldName = courier.getName();
            String oldPassword = courier.getPassword();
            String oldPhone = courier.getPhone();
            String oldEmail = courier.getEmail();
            if (password != null)
                courier.setPassword(password);
            if (phone != null && phone.equals("未绑定"))
                courier.setPhone(null);
            if (name != null)
                courier.setName(name);
            if (email != null)
                courier.setEmail(email);
            try {
                return new Message(CourierService.update(id, courier), "修改成功！").toJSON();
            } catch (DuplicateException e) {
                courier.setPassword(oldPassword);
                courier.setPhone(oldPhone);
                courier.setName(oldName);
                courier.setEmail(oldEmail);
                return new Message(e.getType().getVal(), getMessage(e.getType())).toJSON();
            }
        } else {
            return new Message(-6, "请先登录").toJSON();
        }
    }

    @Body("/wx/checkPass.do")
    public String checkPass(HttpServletRequest req, HttpServletResponse resp) {
        String password = req.getParameter("password");
        User user = UserUtil.getUser(req);
        if (user != null) {
            if (user.getPassword().equals(password))
                return new Message(0).toJSON();
        } else {
            Courier courier = UserUtil.getCourier(req);
            if (courier != null) {
                if (courier.getPassword().equals(password)) {
                    return new Message(0).toJSON();
                }
            } else return new Message(-2, "请先登录").toJSON();
        }
        return new Message(-1, "密码错误").toJSON();
    }

    @Body("/wx/sendMessage.do")
    public String sendMessage(HttpServletRequest req, HttpServletResponse resp) {
        final String phone = req.getParameter("phone");
        String sysCode = (String) req.getSession().getAttribute(phone);
        if (sysCode == null) {
            sysCode = RandomUtil.genStr(6);
            req.getSession().setAttribute(phone, sysCode);
        }
//        if (AlibabaSMSUtil.send(phone, sysCode)) {
        System.out.println("发送一条短信给手机号 " + phone + " , 验证码：" + sysCode);
        return new Message(0, "短信发送成功").toJSON();
//        }
//        return new Message(-1, "短信发送失败").toJSON();
    }

    @Body("/wx/isUserCheckStart.do")
    public String isUserCheckStart(HttpServletRequest req, HttpServletResponse resp) {
        final User user = UserUtil.getUser(req);
        if (user == null) {
            final Courier courier = UserUtil.getCourier(req);
            if (courier.getPhone() != null) {
                return new Message(1, "已认证", courier).toJSON();
            }
        } else {
            if (user.getPhone() != null) {
                return new Message(0, "已认证", user).toJSON();
            }
        }
        return new Message(-1, "未认证").toJSON();
    }

    @Body("/wx/userVerify.do")
    public String userVerify(HttpServletRequest req, HttpServletResponse resp) {
        final String phone = req.getParameter("phone");
        final String msg = req.getParameter("msg");
        final User user = UserUtil.getUser(req);
        final String sysCode = (String) req.getSession().getAttribute(phone);
        if (user != null) {
            String oldPhone = user.getPhone();
            user.setPhone(phone);
            if (sysCode != null && sysCode.equals(msg)) {
                final Message message;
                try {
                    message = new Message(UserService.update(user.getId(), user));
                } catch (DuplicateException e) {
                    user.setPhone(oldPhone);
                    return new Message(e.getType().getVal(), getMessage(e.getType())).toJSON();
                }
                message.setMessage("修改成功！");
                return message.toJSON();
            }
            return new Message(-6, "验证码不正确").toJSON();
        }
        final Courier courier = UserUtil.getCourier(req);
        if (courier != null) {
            String oldPhone = courier.getPhone();
            courier.setPhone(phone);
            if (sysCode != null && sysCode.equals(msg)) {
                final Message message;
                try {
                    message = new Message(CourierService.update(courier.getId(), courier));
                } catch (DuplicateException e) {
                    courier.setPhone(oldPhone);
                    return new Message(e.getType().getVal(), getMessage(e.getType())).toJSON();
                }
                message.setMessage("修改成功！");
                return message.toJSON();
            }
            return new Message(-6, "验证码不正确").toJSON();
        }
        return new Message(-7, "请先登录").toJSON();
    }

    private String getMessage(ExceptionStateEnum e) {
        switch (e) {
            case DUPLICATE_IDENTIFICATION:
                return "该身份证号码已有人注册!";
            case DUPLICATE_NAME:
                return "用户名已被占用";
            case DUPLICATE_EMAIL:
                return "该邮箱地址已被注册";
            case DUPLICATE_PHONE:
                return "该手机号码已被注册";
            default:
                return "操作失败";
        }
    }

    @Body("/wx/getUserInfo.do")
    public String getUserInfo(HttpServletRequest req, HttpServletResponse resp) {
        final User user = UserUtil.getUser(req);
        if (user != null) {
            User newUser = new User();
            newUser.setName(user.getName());
            newUser.setPhone(user.getPhone());
            newUser.setEmail(user.getEmail());
            newUser.setId(user.getId());
            return new Message(0, null, newUser).toJSON();
        }
        final Courier courier = UserUtil.getCourier(req);
        if (courier != null) {
            Courier newCourier = new Courier();
            newCourier.setName(courier.getName());
            newCourier.setPhone(courier.getPhone());
            newCourier.setEmail(courier.getEmail());
            newCourier.setId(courier.getId());
            return new Message(1, null, newCourier).toJSON();
        }
        return new Message(-1, "请先登录").toJSON();
    }

    @View("/log/logout.do")
    public String logout(HttpServletRequest req, HttpServletResponse resp) {
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            if ("autoLogin".equals(cookie.getName())) {
                cookie.setPath("/");
                cookie.setValue(null);
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
                break;
            }
        }
        req.getSession().invalidate();
        return "/login.html";
    }


    @Body("/email/checkEmail.do")
    public String checkEmail(HttpServletRequest req, HttpServletResponse resp) {
        final String email = req.getParameter("email");
        final String name = req.getParameter("name");
        if (email == null || name == null)
            return JSONUtil.toJSON(new Message(-2, "出错了"));
        final User user = UserService.getUserByEmail(email);
        if (user != null && user.getName().equals(name)) {
            req.getSession().setAttribute("user", user);
            return JSONUtil.toJSON(new Message(0, "登录成功"));
        }
        final Courier courier = CourierService.getCourierByEmail(email);
        if (courier != null && courier.getName().equals(name)) {
            req.getSession().setAttribute("courier", courier);
            return JSONUtil.toJSON(new Message(0, "登录成功"));
        }
        return JSONUtil.toJSON(new Message(-1, "验证失败"));
    }


    @Body("/email/login.do")
    public String login(HttpServletRequest req, HttpServletResponse resp) {
        final String name = req.getParameter("name");
        final String password = req.getParameter("password");
        final String autoLogin = req.getParameter("autoLogin");
        final Courier courier = CourierService.login(name, password);
        final User user = UserService.login(name, password);
        if (courier != null && user != null) {
            return JSONUtil.toJSON(new Message(-2, "账号状态异常，请验证邮箱"));
        }
        if (courier != null) {
            req.getSession().invalidate();
            req.getSession().setAttribute("courier", courier);
                // 添加自动登录的 cookie
                Cookie cookie = new Cookie("autoLogin", "true".equals(autoLogin) ? courier.getEmail() : "false");
                cookie.setMaxAge(7 * 24 * 60 * 60);
                cookie.setPath("/");
                resp.addCookie(cookie);
            return JSONUtil.toJSON(new Message(1, "登录成功"));
        }
        if (user != null) {
            req.getSession().invalidate();
            req.getSession().setAttribute("user", user);
            // 添加自动登录的 cookie
            Cookie cookie = new Cookie("autoLogin", "true".equals(autoLogin) ? user.getEmail() : "false");
            cookie.setMaxAge(7 * 24 * 60 * 60);
            cookie.setPath("/");
            resp.addCookie(cookie);
            return JSONUtil.toJSON(new Message(0, "登录成功"));
        }
        return JSONUtil.toJSON(new Message(-1, "用户名或密码错误"));
    }

}
